package com.example.androidstart.homepage;

import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.androidstart.homepage.viewholder.GoodsItemViewHolder;
import com.example.androidstart.homepage.viewholder.HeaderImgViewHolder;
import com.example.androidstart.homepage.viewholder.IconViewHolder;

import java.util.ArrayList;
import java.util.List;

public class HomePageAdapter extends RecyclerView.Adapter<CustomViewHolder> {

    private List<ItemInfo> mItemData = new ArrayList<>();

    private final SparseArray<IViewHolderCreator> mViewHolderCreator = new SparseArray<>();

    {
        mViewHolderCreator.put(ItemType.GOOD_ITEM_TYPE, GoodsItemViewHolder.CREATOR);
        mViewHolderCreator.put(ItemType.ICON_TYPE, IconViewHolder.CREATOR);
        mViewHolderCreator.put(ItemType.BIG_IMG_TYPE, HeaderImgViewHolder.CREATOR);
    }

    public HomePageAdapter(List<ItemInfo> itemInfos) {
        mItemData = itemInfos;
    }

    @NonNull
    @Override
    public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // mViewHolderCreator中存储了不同的viewType对应的不同的viewholderCreator，可以快速创建对应的view
        IViewHolderCreator creator = mViewHolderCreator.get(viewType);
        int layoutId = creator.getLayoutId();
        View itemView = LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
        CustomViewHolder customViewHolder = creator.createViewHolder(itemView);
        customViewHolder.initView();
        return customViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull CustomViewHolder holder, int position) {
        holder.onBind(mItemData.get(position));
    }

    @Override
    public int getItemViewType(int position) {
        // 根据位置先获取具体的item实现，然后获取item的类型
        return mItemData.get(position).getType();
    }

    @Override
    public int getItemCount() {
        // 获取总数
        return mItemData.size();
    }
}
